package ign.gui;

import ign.MyListener;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.Semaphore;
import javax.swing.JPanel;

/**
 * Comportement s'occupant d'afficher graphiquement
 * les agents que l'ihm lui passe.
 * @author Simon Bourigaut & Ghislain Di Paolo
 */
public class Gui extends JPanel {

	private static final long serialVersionUID = -3652103315671155999L;
	private ArrayList<Rectangle> rects;
	private Random rand;
	private Semaphore busy;
	private MyListener listener;
	private int nb_agent_created = 0;
	private int nb_agent_alive = 0;

	/**
	 * Constructeur prenant un MyListener en paramètre, pour compter les agents.
	 * @param listener Le MyListener.
	 */
	public Gui(MyListener listener) {
		
		rects = new ArrayList<Rectangle>();
		busy = new Semaphore(1);
		this.listener = listener;
	}
	
	/** Ajoute un rectangle à afficher */
	public void addRectangle(Rectangle r) {
		
		rects.add(r);
	}
	
	/** Efface la liste d'agents et récupère les informations du listener */
	public void clear() {
		
		try {
			busy.acquire();
			
			rects.clear();
			nb_agent_created = listener.getNbAgentCreated();
			nb_agent_alive = listener.getNbAgentAlive();
			
			busy.release();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void paintComponent(Graphics g){
		Graphics2D g2 = (Graphics2D) g;
		Rectangle size = g2.getClip().getBounds();
		
		g2.setBackground(Color.black);
		g2.clearRect(size.x, size.y, size.width, size.height);
		
		try {
			busy.acquire();
			
			int red, green, blue;
			ArrayList<Rectangle> clone = (ArrayList<Rectangle>) rects.clone();
			for (Rectangle r : clone) {
				rand = new Random(r.width+r.height);
				red = rand.nextInt(165) + 90;
				green = rand.nextInt(155) + 100;
				blue = rand.nextInt(165) + 90;
				g2.setPaint(new Color(red, green, blue));
				g2.drawRect(r.x, r.y, r.width, r.height);
			}
			
			busy.release();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		float dead_perc = (100 - ((float)(nb_agent_created - (nb_agent_created - nb_agent_alive)) / nb_agent_created) * 100);
		g2.drawString("Created : " + nb_agent_created + ", Alive : " + nb_agent_alive + ", %Dead : " + dead_perc, 10, 15);
	}
}
